<template>
  <page-header-wrapper :title="false">
    <div class="Role">
      <a-spin tip="加载中..." class="position" v-if="roleLoading"> </a-spin>
      <a-modal
        width="1200px"
        v-model="detailsVisible"
        title="详情信息"
        @cancel="() => (this.detailsVisible = false)"
        destroyOnClose
      >
        <div class="modalContent">
          <Details :roleData="roleData" :archiveorder="true" @closeDetailModal="closeDetailModal"></Details>
        </div>
        <template slot="footer">
          <Button
            type="reset"
            label="关闭"
            @click="
              () => {
                this.detailsVisible = false;
              }
            "
          ></Button>
        </template>
      </a-modal>
      <a-modal
        width="1000px"
        v-model="powerVisible"
        title="充电功率"
        @cancel="() => (this.powerVisible = false)"
        destroyOnClose
      >
        <div class="modalContent">
          <Power :roleData="roleData" :archiveorder="true"></Power>
        </div>
        <template slot="footer">
          <Button
            type="reset"
            label="关闭"
            @click="
              () => {
                this.powerVisible = false;
              }
            "
          ></Button>
        </template>
      </a-modal>
      <typicalSearch
        ref="insideSearch"
        :searchConfig="searchConfig"
        @searchMethod="getTableData"
        @clearMethod="searchOptListDynamicLoading()"
      ></typicalSearch>
      <div class="table">
        <div class="tableTitle">
          <div class="title">归档订单</div>
          <!-- <div class="addButton">
            <a-button type="primary" @click="() => (this.modleVisible = true)">
              导出
            </a-button>
          </div> -->
        </div>
        <div class="tableList">
          <typicalTable
            ref="insideTable"
            :tableConfig="tableConfig"
            :tableData="tableData"
            @getTableData="getTableData"
          >
            <template v-slot="slotProps">
              <Button label="详情" @click="handleEdit(slotProps.record, 'detailsVisible')"></Button>
              <Button label="充电功率" @click="handleEdit(slotProps.record, 'powerVisible')"></Button>
              <!-- <Button
                type="stop"
                v-if="slotProps.record.chargingOrder.status != -1 && slotProps.record.chargingOrder.status != 30"
                label="结束订单"
                @click="handleEdit(slotProps.record)"
              ></Button> -->
            </template>
          </typicalTable>
        </div>
      </div>
    </div>
  </page-header-wrapper>
</template>
<script>
import { positive } from '@/api/api';
import moment from 'moment';
import typicalSearch from '@/components/typicalSearch';
import typicalTable from '@/components/typicalTable';
import Input from '@/components/typicalControl/Input';
import InputNumber from '@/components/typicalControl/InputNumber';
import treeSelect from '@/components/typicalControl/treeSelect';
import Select from '@/components/typicalControl/select';
import Button from '@/components/typicalControl/button';
import { getListEnumsJson } from '@/utils/frequentInterface';

import { listUserChargings, listNetworksAll, listEnumsByType } from '@/api/cabin';
import { organizationsTree } from '@/api/system';
import { forEach } from 'store/storages/all';

import Power from '../chargingInformation/power.vue';
import Details from '../chargingInformation/details.vue';
export default {
  name: 'ChargingInformation',
  components: {
    typicalSearch: typicalSearch,
    typicalTable: typicalTable,
    Input: Input,
    InputNumber: InputNumber,
    treeSelect: treeSelect,
    Button: Button,
    Select: Select,
    Power: Power,
    Details: Details,
  },
  data() {
    return {
      detailsVisible: false,
      powerVisible: false,
      powerData: [], //功率数据
      roleLoading: false, // 加载表格的loading
      // 搜索组件配置
      searchConfig: {
        formItemList: [
          {
            type: 'selectTree',
            prop: 'searchOrganizationId',
            value: undefined,
            label: '组织机构',
            treeData: [],
            change: this.searchOptListDynamicLoading,
          },
          {
            type: 'select',
            prop: 'searchNetworkId',
            value: undefined,
            label: '场站网点',
            optList: [],
          },
          {
            type: 'rangeDatePicker',
            prop: 'searchBeginTimeStart&searchBeginTimeEnd',
            value: [
              // moment(new Date()).format('YYYY-MM-DD'),
              // moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
              moment().startOf('month').format("YYYY-MM-DD"),
              moment(new Date()).format('YYYY-MM-DD')
            ],
            label: '开始时间',
            isMonth: true,//不能跨月
          },
          {
            type: 'select',
            prop: 'searchBusiness',
            value: undefined,
            label: '订单状态',
            optList: [],
          },
          // {
          //   type: 'select',
          //   prop: 'searchTerminalType',
          //   value: undefined,
          //   label: '终端类型',
          //   optList: [],
          // },
          {
            type: 'input',
            prop: 'searchCabinetCode',
            value: '',
            label: '充电柜编码',
          },
        ],
        parent: this,
      },
      // 列表组件配置
      tableConfig: {
        columns: [
          {
            title: '客户姓名',
            dataIndex: 'userName',
            ellipsis: true,
            width: '150px',
          },
          {
            title: '手机号',
            dataIndex: 'userMobile',
            ellipsis: true,
            width: '120px',
          },
          {
            title: '组织机构',
            dataIndex: 'organizationName',
            ellipsis: true,
            width: '200px',
          },
          {
            title: '场站网点',
            dataIndex: 'networkName',
            ellipsis: true,
            width: '200px',
          },
          {
            title: '充电柜编码',
            dataIndex: 'cabinetCode',
            ellipsis: true,
            width: '200px',
          },
          {
            title: '充电柜名称',
            dataIndex: 'cabinetName',
            ellipsis: true,
            width: '200px',
          },
          {
            title: '格口序号',
            dataIndex: 'binIndex',
            ellipsis: true,
            width: '80px',
          },

          {
            title: '订单编码',
            dataIndex: 'code',
            ellipsis: true,
            width: '200px',
          },
          {
            title: '卡号',
            dataIndex: 'cardCode',
            ellipsis: true,
            width: '160px',
          },
          {
            title: '业务状态',
            dataIndex: 'status',
            ellipsis: true,
            customRender: this.formatterBusinessState,
            width: '120px',
          },
          {
            title: '开始时间',
            dataIndex: 'startTime',
            ellipsis: true,
            customRender: this.formatterTime,
            width: '170px',
          },
          {
            title: '结束时间',
            dataIndex: 'endTime',
            ellipsis: true,
            customRender: this.formatterTime,
            width: '170px',
          },
          {
            title: '计费类型',
            dataIndex: 'chargeType',
            customRender: this.chargeType,
            width: '100px',
          },
          {
            title: '已充电量',
            dataIndex: 'chargingPower',
            customRender: (val) => (val != null ? val + 'kW·h' : ''),
            width: '110px',
          },
          {
            title: '总充电时长',
            dataIndex: 'totalSecond',
            ellipsis: true,
            customRender: this.secondTransformHours,
            width: '150px',
          },
          {
            title: '已充时长',
            dataIndex: 'chargingSecond',
            ellipsis: true,
            customRender: this.secondTransformHours,
            width: '150px',
          },
          // {
          //   title: '充电电量',
          //   dataIndex: 'chargingPower',
          //   ellipsis: true,
          //   width: '200px'
          // },
          // {
          //   title: '充电费用',
          //   dataIndex: 'chargingFees',
          //   ellipsis: true,
          //   customRender: (val) => (val ? val + '元' : ''),
          //   width: '200px',
          // },
          {
            title: '电费费用',
            dataIndex: 'billDetail.powerFees',
            ellipsis: true,
            customRender: (val) => (val != null ? val + '元' : '0元'),
            width: '125px',
          },
          {
            title: '服务费用',
            dataIndex: 'billDetail.serviceFees',
            ellipsis: true,
            customRender: (val) => (val != null ? val + '元' : '0元'),
            width: '125px',
          },
          {
            title: '占仓费用',
            dataIndex: 'billDetail.occupyCabinetFees',
            ellipsis: true,
            customRender: (val) => (val != null ? val + '元' : '0元'),
            width: '125px',
          },
          {
            title: '支付金额',
            ellipsis: true,
            dataIndex: 'billDetail.totalBill',
            customRender: (val) => (val != null ? val + '元' : '0元'),
            width: '125px',
          },
          // {
          //   title: '终端类型',
          //   dataIndex: 'chargingOrder.terminalType',
          //   customRender: this.formatterTerminalType,
          //   width: '100px',
          // },
          {
            title: '接收时间',
            dataIndex: 'receiveTime',
            ellipsis: true,
            customRender: this.formatterTime,
            width: '200px',
          },
          {
            title: '操作',
            scopedSlots: { customRender: 'action' },
            fixed: 'right',
            width: '200px',
          },
        ],
        pageSize: this.$store.state.user.defaultPaginationPagesize,
        pageSizeOptions: this.$store.state.user.defaultPaginationOptions,
        parent: this,
        scrollX: 3200,
      },
      // 列表组件数据
      tableData: {
        records: [],
        total: 0,
      },
      enumsType: ['CHARGING_ORDER_STATUS', 'PAY_MODE'],
      enumsTypeJson: {},
      oDictionary: {
        listNetworksAll: [],
      },
      roleData: {}, //行信息
      searchParam: {}, //查询信息
    };
  },
  created() {
    this.getDictionary();
  },
  mounted() {
    this.$refs.insideSearch.searchInfo();
  },
  methods: {
    closeDetailModal() {
      this.detailsVisible = false;
    },
    /**
     * [getDictionary 获取各种字典]
     * @return {[type]} [description]
     */
    getDictionary() {
      // this.enumsTypeJson = getListEnumsJson();
      // 组织列表树形结构数据
      organizationsTree().then((res) => {
        if (res.code == 200) {
          for (var i = 0; i < this.searchConfig.formItemList.length; i++) {
            if (this.searchConfig.formItemList[i].prop == 'searchOrganizationId') {
              this.searchConfig.formItemList[i].treeData = res.data;
              break;
            }
          }
        }
      });
      this.getNetworkData();

      listEnumsByType().then((res) => {
        let datas = res.data;
        for (const key in datas) {
          for (var i = 0; i < datas[key].length; i++) {
            datas[key][i].name = datas[key][i].label;
          }
        }
        this.enumsTypeJson = datas;
        // 终端类型
        for (var i = 0; i < this.searchConfig.formItemList.length; i++) {
          if (this.searchConfig.formItemList[i].prop === 'searchTerminalType') {
            this.searchConfig.formItemList[i].optList = this.enumsTypeJson['TERMINAL_TYPE'];
          } else if (this.searchConfig.formItemList[i].prop === 'searchBusiness') {
            this.searchConfig.formItemList[i].optList = this.enumsTypeJson['CHARGING_ORDER_STATUS'];
          }
        }
      });
    },
    getNetworkData(organizationId) {
      // 场站网点
      listNetworksAll(`/selectChargingnetwork`, 'get', {
        pageNum: 1,
        pageSize: 100,
        organizationId: organizationId,
      }).then((res) => {
        if (res.code == 200) {
          this.oDictionary.listNetworksAll = res.data.records.map((n) => {
            return {
              name: n.name,
              code: n.id,
            };
          });
          for (var i = 0; i < this.searchConfig.formItemList.length; i++) {
            if (this.searchConfig.formItemList[i].prop == 'searchNetworkId') {
              this.searchConfig.formItemList[i].optList = this.oDictionary.listNetworksAll;
              break;
            }
          }
        }
      });
    },
    /**
     * [searchOptListDynamicLoading 搜索下拉动态加载]
     * @param  {[type]} searchOrganizationId [组织机构id]
     * @return {[type]}                      [description]
     */
    searchOptListDynamicLoading(searchOrganizationId) {
      this.oDictionary.listNetworksAll = [];

      this.getNetworkData(searchOrganizationId);
    },
    /**
     * [getTableData 获取表格数据]
     * @param  {[type]} searchParam [搜索条件]
     * @return {[type]}             [description]
     */
    getTableData(searchParam) {
      this.searchParam = searchParam;
      let params = searchParam ? { ...searchParam } : {};
      this.roleLoading = true;
      let searchData = {
        pageNum: params.pageNumber ? params.pageNumber + 1 : 1,
        pageSize: params.pageSize ? params.pageSize : 10,
        organizationId: params.searchOrganizationId,
        networkId: params.searchNetworkId,
        status: params.searchBusiness,
        cabinetCode: params.searchCabinetCode,
      };

      if (params.searchBeginTimeStart) {
        searchData.startCreateTime = params.searchBeginTimeStart + ' 00:00:00';
        searchData.endCreateTime = params.searchBeginTimeEnd + ' 23:59:59';
      }
      listUserChargings('/order/history/infos', 'post', searchData)
        .then((res) => {
          if (res.code == 200) {
            this.tableData.total = Number(res.total);
            this.tableData.records = res.data;
          } else {
            this.tableData.records = [];
            this.tableData.total = 0;
          }
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    /**
     * [formatterTime 格式化时间戳]
     * @param  {[type]} val [description]
     * @return {[type]}     [description]
     */
    formatterTime(val) {
      return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '';
    },
    chargeType(val) {
      let chargeData = {
        DURATION: '按时',
        QUANTITY: '按电量',
      };
      return chargeData[val];
    },
    /**
     * [secondTransformHours 秒转小时分秒]
     * @param  {[type]} val [description]
     * @return {[type]}     [description]
     */
    secondTransformHours(val) {
      var result;
      if (val) {
        result = '';
        const h = parseInt(val / 3600);
        const m = parseInt((val % 3600) / 60);
        const s = parseInt((val % 3600) % 60);
        if (h) result = h + '小时';
        if (m) result = result + m + '分';
        if (s) result = result + s + '秒';
      } else {
        result = '0秒';
      }
      return result;
    },
    /**
     * [calculationMoney 计算支付金额]
     * @param  {[type]} row [行数据]
     * @return {[type]}     [description]
     */
    calculationMoney(row) {
      var val = 0;
      const k = 100;
      const chargeFees = Number(row.chargeFees) * k;
      const occupyFees = Number(row.occupyFees) * k;
      const serviceFees = Number(row.serviceFees) * k;
      // if (row.isPayChargingFees === 1) {
      //   val = val + chargingFees;
      // }
      // if (row.isPayOccupyFees === 1) {
      //   val = val + occupyFees;
      // }
      val = chargeFees + occupyFees + serviceFees;
      return val ? val / k + '元' : '';
    },
    /**
     * [formatterBusinessState 格式化业务状态]
     * @param  {[type]} val [description]
     * @return {[type]}     [description]
     */
    formatterBusinessState(val) {
      var result = '';
      for (var i = 0; i < this.enumsTypeJson['CHARGING_ORDER_STATUS'].length; i++) {
        if (val == this.enumsTypeJson['CHARGING_ORDER_STATUS'][i].code) {
          result = this.enumsTypeJson['CHARGING_ORDER_STATUS'][i].name;
          break;
        }
      }
      return result;
    },
    formatterTerminalType(val) {
      var result = '';
      if (val && this.enumsTypeJson['PAY_MODE']) {
        for (var i = 0; i < this.enumsTypeJson['PAY_MODE'].length; i++) {
          if (val === this.enumsTypeJson['PAY_MODE'][i].code) {
            result = this.enumsTypeJson['PAY_MODE'][i].name;
            break;
          }
        }
      }
      return result;
    },
    /**
     * [confirmAgain 再次确定提示框]
     * @param  {[type]} row [description]
     * @return {[type]}     [description]
     */
    confirmAgain(row) {
      const cabinet = row.cabinet ? row.cabinet.name : '充电柜';
      const binIndex = row.cabinet ? row.bin.binIndex : '';
      this.$confirm({
        title: '终止订单',
        content: (h) => cabinet + '第 ' + binIndex + ' 格口将被终止订单，此操作不可逆是否继续？',
        onOk: () => this.handleTermination(row),
        class: 'test',
        centered: true,
        maskClosable: true,
      });
    },
    /**
     * [handleTermination 终止订单]
     * @param  {[type]} row [行数据]
     * @return {[type]}     [description]
     */
    handleTermination(row) {
      this.roleLoading = true;
      positive({ id: row.id })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.$refs.insideTable.updateListData();
          }
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    handleEdit(row, instructions) {
      // this.currentId = String(row.id);
      if (instructions) this[instructions] = true;
      else
        this.$confirm({
          title: '提示',
          content: (h) => '确定要结束该订单吗？',
          onOk: () => this.doCancleOrder(),
          centered: true,
          maskClosable: true,
        });
      this.roleData = row;
    },
    // 取消订单
    doCancleOrder() {
      listUserChargings('/charging/finish', 'get', { orderId: this.roleData.chargingOrder.id, flag: 0 })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.getTableData(this.searchParam);
          }
        })
        .finally(() => {});
    },
  },
};
</script>

<style lang="less" scoped>
.Role {
  width: 100%;
  height: calc(100vh - 150px);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  position: relative;
  .position {
    width: 100%;
    height: 100%;
    background: white;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }
  .table {
    flex: 1;
    background: white;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    .tableTitle {
      width: 100%;
      height: 64px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ececec;
      padding: 0 20px;
      margin-bottom: 10px;
      .title {
        width: 80%;
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 550;
      }
      .addButton {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
    .tableList {
      // max-height: calc(100vh - 380px);
      // overflow: auto;
      /deep/ .tableScroll {
        max-height: calc(100vh - 380px);
        overflow: auto;
      }
    }
  }
}
.modalContent {
  width: 100%;
  height: 620px;
  position: relative;
  .formAspin {
    position: absolute;
    width: 100%;
    height: 300px;
    background: #ececec;
    border-radius: 4px;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
/deep/ .ant-input {
  padding: 4px 6px;
}
/deep/ .ant-col-4 {
  width: 20%;
}
</style>
